package servlet;

import bean.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class Register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("register succeed");
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.设置请求和响应的编码格式，以及响应的格式
        request.setCharacterEncoding("utf-8"); // 设置获取数据的格式
        response.setCharacterEncoding("utf-8");

        // 2.获取请求的参数
        String username = request.getParameter("username"); //根据表单的name属性获取用户输入的账号密码
        String password = request.getParameter("password");
        System.out.println(username);
        System.out.println(password);

        // 封装：把上面所有变量装载到User对象中
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 3.执行业务处理
        UserDao userDao = new UserDao();
        int row = userDao.register(user);

        // 4.做出响应
        if (row > 0) {
            // 注册成功,跳转到登录页
            response.sendRedirect("login.jsp");
        } else {
            // 注册失败，传入错误信息并跳转页面
            request.setAttribute("error_msg","注册失败！请刷新页面或重新打开浏览器！");
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }
}
